package com.sunnos.express.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sunnos.express.entity.Right;
import com.sunnos.express.entity.Role;

public class RightFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rsp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
//		System.out.println("filter�������������������������������������������......��9�ص�����URL�ǣ�"+req.getRequestURI());
		if (req.getRequestURI().indexOf("index.jsp")<0) {
			Role role = (Role)session.getAttribute("loginUserRole");
			if (role!=null) {
				if (req.getRequestURI().indexOf("main.jsp")<0) {
					List<Right> rights = role.getRights();
					if (rights!=null) {
						for (int i=0;i<rights.size();i++) {
							Right right = rights.get(i);
//							System.out.println("9���������������������������������������������...... �û�ӵ�е�Ȩ��URL�ǣ�"+right.getUrl()+","+req.getRequestURI().indexOf(right.getUrl()));
							if (req.getRequestURI().indexOf(right.getUrl())>0) {
								chain.doFilter(request, response);
								return;
							}
						}
					}
				}
				else {
					chain.doFilter(request, response);
					return;
				}
			}
			rsp.sendRedirect(req.getContextPath()+"/index.jsp");
			return;
		}
		else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
